import { getConfigByKey } from "@/api/system/config";

const stateData = {
  isShowTags: true,
  isCollapse: false,
  layoutSize: "small",
  themeColor: "#FF6A6C",
  themeStyle: "dark",
  systemLogo: undefined,
  systemTitle: undefined,
  greetings: undefined,
  currentRoute: "",
  routes: [],
  allowUrls: "", // 子行业允许访问的url
  noticePushQueues: JSON.parse(localStorage.getItem("noticePushQueues")) || [],
  noticeQueuesIframes:
    JSON.parse(localStorage.getItem("noticeQueuesIframes")) || {},
  commonNoticePushQueues:
    JSON.parse(localStorage.getItem("commonNoticePushQueues")) || [], // 通用消息提示队列
  commonNoticeQueuesIframes:
    JSON.parse(localStorage.getItem("commonNoticeQueuesIframes")) || {}, // 通用消息提示队列iframe
  noticeRedirectQueues: undefined, // 消息跳转队列
  noticeRedirectQueueData: undefined, // 消息跳转信息
  systemSocketData: undefined, // 主websocket接受的信息
  splitScreenRouting: "", // 分频路由
  dialogVideoRouting: "", // 弹窗分频路由
};

const mutations = {
  SET_SHOW_TAGS: (state, isShowTags) => {
    state.isShowTags = isShowTags;
  },
  SET_CURRENTROUTE: (state, currentRoute) => {
    state.currentRoute = currentRoute;
  },
  SET_COLLAPSE: (state, isCollapse) => {
    state.isCollapse = isCollapse;
  },
  SET_LAYOUT_SIZE: (state, layoutSize) => {
    if (layoutSize) {
      state.layoutSize = layoutSize;
    }
  },
  SET_THEME_COLOR: (state, themeColor) => {
    if (themeColor) {
      state.themeColor = themeColor;
    }
  },
  SET_THEME_STYLE: (state, themeStyle) => {
    if (themeStyle) {
      state.themeStyle = themeStyle;
    }
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes;
  },
  SET_SYSTEM_LOGO: (state, logo) => {
    state.systemLogo = logo;
  },
  SET_SYSTEM_TITLE: (state, title) => {
    state.systemTitle = title || "中国铁塔视联平台";
  },
  SET_GREETINGS: (state, greetings) => {
    state.greetings = greetings;
  },
  ADD_NOTICE_PUSH_QUEUES: (state, { data }) => {
    let queues = JSON.parse(localStorage.getItem("noticePushQueues")) || [];
    queues.push(data.industryCode + "");
    const _queues = new Set(queues);
    localStorage.setItem("noticePushQueues", JSON.stringify([..._queues]));
    state.noticePushQueues = [..._queues];

    let noticeQueuesIframes =
      JSON.parse(localStorage.getItem("noticeQueuesIframes")) || {};
    noticeQueuesIframes[data.industryCode] = data.originIframeId;
    localStorage.setItem(
      "noticeQueuesIframes",
      JSON.stringify(noticeQueuesIframes)
    );
    state.noticeQueuesIframes = noticeQueuesIframes;
  },
  REMOVE_NOTICE_PUSH_QUEUES: (state, { data }) => {
    let queues = JSON.parse(localStorage.getItem("noticePushQueues")) || [];
    queues = queues.filter((item) => item !== data.industryCode + "");
    localStorage.setItem("noticePushQueues", JSON.stringify(queues));

    state.noticePushQueues = queues;
  },
  // 通用消息提示队列 Mark.Yuan 2023.05.15
  ADD_COMMON_NOTICE_PUSH_QUEUES: (state, { data }) => {
    let queues =
      JSON.parse(localStorage.getItem("commonNoticePushQueues")) || [];
    const index = queues.findIndex(
      (item) => item.industryCode === data.industryCode
    );
    if (index > -1) {
      // 如果已经添加过，则进行修改
      queues[index] = {
        industryCode: data.industryCode, // 行业编码
        type: data.type, // 推送的消息类型
      };
    } else {
      // 反之，则追加
      queues.push({
        industryCode: data.industryCode, // 行业编码
        type: data.type, // 推送的消息类型
      });
    }

    const _queues = new Set(queues);
    localStorage.setItem(
      "commonNoticePushQueues",
      JSON.stringify([..._queues])
    );
    state.commonNoticePushQueues = [..._queues];

    let noticeQueuesIframes =
      JSON.parse(localStorage.getItem("commonNoticeQueuesIframes")) || {};
    noticeQueuesIframes[data.industryCode] = data.originIframeId;
    localStorage.setItem(
      "commonNoticeQueuesIframes",
      JSON.stringify(noticeQueuesIframes)
    );
    state.commonNoticeQueuesIframes = noticeQueuesIframes;
  },
  // 通用消息提示队列iframe Mark.Yuan 2023.05.15
  REMOVE_COMMON_NOTICE_PUSH_QUEUES: (state, { data }) => {
    let queues =
      JSON.parse(localStorage.getItem("commonNoticePushQueues")) || [];
    queues = queues.filter((item) => item.industryCode !== data.industryCode);
    localStorage.setItem("commonNoticePushQueues", JSON.stringify(queues));
    state.commonNoticePushQueues = queues;
  },
  NOTICE_REDIRECT_QUEUES: (state, data) => {
    state.noticeRedirectQueues = `${data.pageRouter}@${data.industryCode}@${data.msgId}`;
  },
  SET_NOTICE_REDIRECT_QUEUE_DATA: (state, data) => {
    state.noticeRedirectQueueData = data;
  },
  SET_SYSTEM_SOCKET_DATA: (state, data) => {
    state.systemSocketData = data;
  },
  SPLIT_SCREEN_ROUTING: (state, data) => {
    state.splitScreenRouting = data;
  },
  SET_ALLOW_URL: (state, data) => {
    state.allowUrls = data;
  },
  DIALOG_VIDEO_ROUTING: (state, data) => {
    state.dialogVideoRouting = data;
  },
};

const actions = {
  setCurrentRoute({ commit }, currentRoute) {
    commit("SET_CURRENTROUTE", currentRoute);
  },
  setShowTags({ commit }, isShowTags) {
    commit("SET_SHOW_TAGS", isShowTags);
  },
  setCollapse({ commit }, isCollapse) {
    commit("SET_COLLAPSE", isCollapse);
  },
  setLayoutSize({ commit }, layoutSize) {
    commit("SET_LAYOUT_SIZE", layoutSize);
  },
  setThemeColor({ commit }, color) {
    commit("SET_THEME_COLOR", color);
    if (color) {
      $("body")[0].style.setProperty("--theme", color);
    }
  },
  setThemeStyle({ commit }, style) {
    commit("SET_THEME_STYLE", style);
  },
  getRouters({ commit }) {
    return new Promise((resolve, reject) => {
      // 向后端请求路由数据
      getRouters()
        .then((res) => {
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].name == "/layout/indexPermission") {
              sessionStorage.setItem("indexPermission", "1");
            }
          }
          let arr = [];
          arr = res.data.filter((item) => {
            return item.name != "/layout/indexPermission";
          });
          // console.log('动态获取路由--->', JSON.stringify(arr))
          const accessedRoutes = formatRouter(arr);
          accessedRoutes.push({
            path: "*",
            redirect: "/error/404",
            hidden: true,
            name: "/error/404",
          });
          commit("SET_ROUTES", constantRoutes.concat(accessedRoutes));
          resolve(accessedRoutes);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  // 注册通知推送
  addNoticePushQueues({ commit }, data) {
    // data 中包含industryCode 行业编码
    commit("ADD_NOTICE_PUSH_QUEUES", data);
  },
  // 移除通知推送
  removeNoticePushQueues({ commit }, data) {
    commit("REMOVE_NOTICE_PUSH_QUEUES", data);
  },
  // 注册通用带类型通知推送 Mark.Yuan 2023.05.16
  addCommonNoticePushQueues({ commit }, data) {
    // data 中包含industryCode 行业编码
    commit("ADD_COMMON_NOTICE_PUSH_QUEUES", data);
  },
  // 移除通用带类型通知推送 Mark.Yuan 2023.05.16
  removeCommonNoticePushQueues({ commit }, data) {
    commit("REMOVE_COMMON_NOTICE_PUSH_QUEUES", data);
  },
  noticeRedirectQueues({ commit }, data) {
    commit("NOTICE_REDIRECT_QUEUES", data);
    commit("SET_NOTICE_REDIRECT_QUEUE_DATA", data);
  },
  // 设置主websocket 接受的信息
  setSystemSocketData({ commit }, data) {
    commit("SET_SYSTEM_SOCKET_DATA", data);
  },
  setSplitScreenRouting({ commit }, data) {
    commit("SPLIT_SCREEN_ROUTING", data);
  },
  setDialogVideoRouting({ commit }, data) {
    commit("DIALOG_VIDEO_ROUTING", data);
  },
  /**
   * 获取允许嵌入的url地址
   * @param {*} commit
   * @param {*} data
   * @returns
   */
  getAllowUrl({ state, commit }) {
    return new Promise((resolve, reject) => {
      if (state.allowUrls) {
        resolve(state.allowUrls);
        return;
      }
      getConfigByKey("sys.allow_urls")
        .then(({ code, data }) => {
          if (code === 200) {
            commit("SET_ALLOW_URL", data?.configValue || "");
          }
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
};
export default {
  namespaced: true,
  state: stateData,
  mutations,
  actions,
};
